package xju_9_10.controller;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import xju_9_10.entity.User;
import xju_9_10.mapper.UserMapper;
import xju_9_10.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
public class MyController {

    @Autowired
    private UserService userService;

    @RequestMapping("/exception")
    public String test() {
        int a =10/0;
        return "hello";
    }


    @RequestMapping("/tologin")
    public String test1(){
        return "login";
    }

    @RequestMapping("/login")
    public String test11(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
        User user = userService.login(username,password);
        if(user!=null){
            session.setAttribute("user",user);
            return "hello";
        }
        return "login";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        String originalFilename = file.getOriginalFilename();
        File file1 = new File(request.getSession().getServletContext().getRealPath("/upload"), originalFilename);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        file.transferTo(file1);
        return file1.getAbsolutePath();
    }

    // 下载
    @RequestMapping("/download")
    public void downLoad(HttpServletResponse response, String fileName, HttpServletRequest request) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        File file = new
                File(request.getSession().getServletContext().getRealPath("/upload"), "uninstallerIcon.ico");
        System.out.println("文件：" + file.getAbsolutePath());
        byte[] data = FileUtils.readFileToByteArray(file);
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment;filename=" + new
                String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.getOutputStream().write(data);
    }


}
